<template>
    <div class="app-container">
        <levelbar></levelbar>
        <div class="form-box" v-loading='loading'>
            <div class="form-title">新增学生</div>
            <el-form :model="dataForm" :rules="rules" ref="dataForm" label-width="80px" class="form" label-position='right'>
                <div class="form-item">
                    <div class="form-item-title">
                        <!-- <span class="note-css"></span> -->
                        <span class="title-level">学校班级信息</span>
                    </div>
                    <div class="form-content">
                        <el-row :gutter="21">
                            <el-col :span="12" v-if="this.schoolType == '0'">
                                <el-form-item label="年级" prop="grade" :rules="rules.schoolName">
                                    <el-select v-if="roleType == '2' || roleType == '1'" v-model="dataForm.grade" :clearable="roleType == '2' || roleType == '1'" placeholder="请选择" style="width:95%;" @change="getClassListFu( dataForm.grade )">
                                        <el-option v-for="item in gradeList" :key="item.pId" :label="item.sName" :value="item.pId">
                                        </el-option>
                                    </el-select>
                                    <el-select v-if="roleType == '5'" v-model="dataForm.grade" placeholder="请选择" style="width:95%;" @change="getClassListFu1( dataForm.grade )">
                                        <el-option v-for="item in gradeList" :key="item.gradeId" :label="item.gradeName" :value="item.gradeId">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="班级名称" prop="classId" :rules="rules.schoolName">
                                    <el-select v-if="roleType == '2' || roleType == '1'" v-model="dataForm.classId" :clearable="roleType == '2' || roleType == '1'" placeholder="请选择" style="width:95%;">
                                        <el-option v-for="item in classList" :key="item.classId" :label="item.classNickName" :value="item.classId">
                                        </el-option>
                                    </el-select>
                                    <el-select v-if="roleType == '5'" v-model="dataForm.classId" placeholder="请选择" style="width:95%;">
                                        <el-option v-for="item in classList" :key="item.classId" :label="item.className" :value="item.classId">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </div>
                </div>
                <div class="form-item">
                    <div class="form-item-title">
                        <!-- <span class="note-css"></span> -->
                        <span class="title-level">基本信息</span>
                    </div>
                    <div class="form-content">
                        <el-row :gutter="21">
                            <el-col :span="12">
                                <el-form-item label="学生姓名" prop="studentName" :rules="rules.studentName">
                                    <el-popover
                                        placement="top-start"
                                        trigger="focus" 
                                        content="长度在12个字符以内。">
                                        <el-input v-model="dataForm.studentName" slot="reference" :maxlength="12" style="width:95%;"></el-input>
                                    </el-popover>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="学籍号" prop="studentCode" :rules="rules.studentCode">
                                    <el-popover
                                        placement="top-start"
                                        trigger="focus" 
                                        content="长度在20个字符以内。">
                                        <el-input v-model="dataForm.studentCode" slot="reference" :maxlength="20" style="width:95%;"></el-input>
                                    </el-popover>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="21">
                            <el-col :span="12">
                                <el-form-item label="出生年月" prop="birthday" :rules="rules.birthday">
                                    <el-date-picker v-model="dataForm.birthday" style="width:95%;" type="date" placeholder="选择日期" :picker-options="pickerOptions0">
                            </el-date-picker>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="性别" prop="sex" :rules="rules.sex">
                                    <el-radio-group v-model="dataForm.sex">
                                        <el-radio label="0">男</el-radio>
                                        <el-radio label="1">女</el-radio>
                                    </el-radio-group>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </div>
                </div>
                <div class="form-item">
                    <div class="form-item-title">
                        <!-- <span class="note-css"></span> -->
                        <span class="title-level">家长信息</span>
                    </div>
                    <div class="form-content item">
                        <el-row :gutter="21" v-for="(item, index) in dataForm.contactWayList" :key="index">
                            <el-col :span="12">
                                <el-form-item :label="'联系人 ' + (index + 1)" :prop="'contactWayList.' + index + '.phone'"  :rules="index==0?rules.contactWay:rules.otherContactWay">
                                    <el-popover
                                    placement="top-start"
                                    trigger="focus" 
                                    content="长度在11个字符以内。">
                                        <el-input v-model="item.phone" slot="reference" :maxlength="11" style="width:95%;"></el-input>
                                    </el-popover>
                                </el-form-item>
                            </el-col>
                            <el-col :span="1" v-if="index != 0">
                                <el-button type="text" class="delBtn" @click="removeContactWay(index)"><i class="el-icon-delete"></i></el-button>
                            </el-col>
                        </el-row>
                        <el-button v-if="dataForm.contactWayList.length < 5" type="text" @click="addContactWay" class="addBtn btn-success"><i class="el-icon-plus"></i> 继续添加</el-button>
                        <!-- <el-row :gutter="21">
                            <el-col :span="12">
                                <el-form-item label="联系方式" prop="contactWay" :rules="rules.contactWay">
                                    <el-input v-model="dataForm.contactWay" style="width:95%;" :maxlength="11"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row> -->
                    </div>
                </div>
                <div class="form-item">
                    <el-row>
                        <el-col :span="24">
                            <el-form-item>
                                <div class="footer">
                                    <el-button @click="resetForm('dataForm')">取消</el-button>
                                    <el-button type="primary" @click="submitForm('dataForm')">确认</el-button>
                                </div>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </div>
            </el-form>
        </div>
    </div>
</template>

<script>
import { isEmpty } from 'utils/validate';
import moment from 'moment';
import Levelbar from "../../layout/Levelbar";
import {
  getGradeInfoByUserIdAndSchoolId, 
  getClassInfoList,
  getLoginRoleInfo, 
  getUserInfoDetail,
  getGradeList, 
  getClassList,
  addStudent,
  querySchoolByName,
  getGrade,
  getClass
} from "api/studentMange";
import { mapGetters } from "vuex";
import validate from '@/utils/validate';

export default {
    name: 'addStudentPage',
    components: { Levelbar },
    data() {
        const validateEmpty = (rule, value, callback) => {
            if (!isEmpty(value)) {
                callback(new Error('内容中不能存在空格'));
            } else {
                callback();
            }
        };
        return {
            dataForm: {
                // 学校班级信息
                schoolName: "",
                grade: "",
                classId: "",

                // 基本信息：
                studentName: "",
                studentCode: "",
                birthday: "",
                sex: "",

                // 家长信息
                contactWay: "",
                contactWayList: [{
                    phone: ''
                }]
            },
            loading: false,
            roleState: '',
            userId: '',
            schoolLoading: false,
            // schoolList: [],
            gradeList: [],
            classList: [],
            pickerOptions0: {
                disabledDate(time) {
                    return time.getTime() > Date.now() - 8.64e7;
                }
            },
            rules: {
                // 学校班级信息
                schoolName: [
                    { required: true, message: "内容不能为空", trigger: "blur" }
                ],

                // 基本信息：
                studentName: [
                    { required: true, message: "请输入学生姓名", trigger: "blur" },
                    { required: true, trigger: 'blur', validator: validateEmpty },
                    { min: 1, max: 12, message: "长度在12个字符以内", trigger: "blur" }
                ],
                studentCode: [
                    { pattern: /^[A-Za-z0-9]+$/, message: '只允许输入数字和字母'},
                    { min: 1, max: 20, message: "长度在20个字符以内", trigger: "blur" }
                ],

                // 家长信息
                contactWay: [
                    ...validate.phoneRequired()
                ],
                otherContactWay: [
                    ...validate.phone()
                ]
            }
        };
    },
  computed: {
    ...mapGetters([
        "uid",
        'schoolId',
        'schoolName',
        'schoolList',
        'schoolType',
        'roleType'
    ])
  },
  created() {
      this.getUserInfoDetailFu();
  },
  methods: {
    addContactWay() {
        this.dataForm.contactWayList.push({
          phone: ''
        });
    },
    removeContactWay(index) {
        if (index !== -1) {
          this.dataForm.contactWayList.splice(index, 1);
        }
    },
    submitForm(dataForm) {
        let phoneArray = [];
        this.dataForm.contactWayList.forEach(item => {
            if(item.phone) {
                phoneArray.push(item.phone);
            }
        });
        const items = new Set(phoneArray);
        if(items.size != phoneArray.length) {
            this.$message.error('联系人号码重复');
            return;
        }
        this.$refs[dataForm].validate(valid => {
            if (valid) {
                let phones = [];
                this.dataForm.contactWay = this.dataForm.contactWayList[0].phone;
                if(this.dataForm.contactWayList.length >1) {
                    this.dataForm.contactWayList.forEach(function(item, index) {
                        if(index != 0 && item.phone) {
                            phones.push(item.phone);
                        }
                    });
                }
                let userId = this.uid; // 创建人ID
                let schoolId = this.schoolId;
                let schoolName = this.schoolName;
                let gradeId = this.dataForm.grade; //  年级
                let classId = this.dataForm.classId; // 班级编号
                let studentName = this.dataForm.studentName; // 学生姓名
                let studentSex = this.dataForm.sex; //  性别
                let schoolrollCode = this.dataForm.studentCode; // 学籍号
                let birthDay = this.dataForm.birthday==''?'':moment(this.dataForm.birthday).format('YYYY-MM-DD'); // 生日
                let parentPhone = this.dataForm.contactWay; // 家长号码
                
                this.loading = true;
                addStudent(
                    userId,
                    schoolId,
                    schoolName,
                    gradeId,
                    classId,
                    studentName,
                    studentSex,
                    schoolrollCode,
                    birthDay,
                    parentPhone,
                    phones
                ).then(response => {
                    this.loading = false;
                    if (response.data.status == 200) {
                        this.$message.success(response.data.errorMsg);
                        this.$refs[dataForm].resetFields();
                        this.$router.push({ path: `/studentManage` });
                        this.$store.dispatch('UpdateCache');
                    } else {
                        this.$message.error(response.data.errorMsg);
                    }
                }).catch(() => {
                    this.loading = false;
                });
            } else {
                return false;
            }
        });
    },
    resetForm(dataForm) {
        this.$refs[dataForm].resetFields();
        this.$router.push({ path: "/studentManage" });
    },

    getUserInfoDetailFu() {
        getUserInfoDetail().then( res => {
            if (res.data.status == 200) {
                this.roleState = res.data.content[0].userType;

                // 2代表学校管理员  5代表班主任
                if (this.roleType == '5' ) { // 5 班主任 6 // 学校管理员
                    this.userId = res.data.content[0].userId;
                    this.getGradeListFu1(this.schoolId);
                } else {
                    this.getGradeListFu(this.schoolId);
                }
            } else {
                this.$message.error(res.data.errorMsg);
            }
        })
    },
    getGradeListFu(schoolId) {
        this.gradeList = [];
        this.dataForm.grade = '';
        if(this.schoolId) {
            if(this.schoolType == '1') {
                this.classList = [];
                this.dataForm.classId = ''; 
                getClassList(null, this.schoolId).then( res => {
                    this.classList = res.data.content;
                })
            } else {
                getGradeList(schoolId).then( res => {
                    this.gradeList = res.data.content;
                })
            }
                
        }
    },
    getClassListFu(gradeId) {
        this.classList = [];
        this.dataForm.classId = ''; 
      
        if(this.dataForm.grade) {
            getClassList(gradeId, this.schoolId).then( res => {
                this.classList = res.data.content;
            })
        }
    },
    getGradeListFu1(schoolId) {
        this.dataForm.grade = '';        
        let userId = this.userId;

        if(this.schoolType == '1') {
            this.dataForm.classId = '';
            getClassInfoList(userId,  null, this.schoolId).then( res => {
                this.classList = res.data.content;
            })
        } else {
            getGradeInfoByUserIdAndSchoolId(userId, schoolId).then( res => {

                this.gradeList = res.data.content;
                for (var i = 0;i<this.gradeList.length;i++) {  
                    for (var j = i+1;j<this.gradeList.length;j++) {  
                        if(this.gradeList[i].gradeId == this.gradeList[j].gradeId){  
                            this.gradeList.splice(j,1);  
                            j--;  
                        }  
                    }  
                }
            })
        }
    },
    getClassListFu1(gradeId) {
        this.dataForm.classId = '';
        let userId = this.userId;
        getClassInfoList(userId,  gradeId, this.schoolId).then( res => {
            this.classList = res.data.content;
        })
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.app-container {
  position: relative;
  padding: 20px 20px 10px;
  $bgcolor: #fff;

  @mixin showTitle() {
    background: $bgcolor;
    box-shadow:  0px 0px 5px 0px rgba(0, 0, 0, 0.1);
    -webkit-box-shadow:  0px 0px 5px 0px rgba(0, 0, 0, 0.1);
  }
    .delBtn {
        font-size: 20px;
        color:#999;
    }
    .addBtn{
        margin-left:80px;
        font-size:14px;
        color:#ff5e2c;
    }
  .form-box {
    padding: 0 50px;
    @include showTitle();
    .form-title {
      padding-top:8px;
      text-align: center;
      font-size: 18px;
      color: #333;
      line-height: 72px;
      font-weight: bold;
      font-family: Microsoft YaHei;
      border-bottom: 1px solid #ddd;
    }
    .form {
      .form-item {
        padding-bottom: 40px;
        .form-item-title {
            margin: 40px 0;
            font-size: 14px;
            color: #333;
            line-height: 14px;
            border-left: 4px solid #ff5e2c;
            text-indent: 16px;
           
          .note-css {
            vertical-align: middle;
            display: inline-block;
            width: 4px;
            height: 14px;
            margin-right: 26px;
            border-left: 3px solid #ff5e2c;
            // background: #30B08F url('../../../images/student/noteLavel.png') no-repeat 0 0;
          }
        }
        .form-content {
            margin: 0 8px;
        }
        .item {
          margin-bottom: 20px;
        }
        .back {
          margin-top: 20px;
        }
        .footer {
          //float: right;
          text-align: center;
          margin-top: 40px;
        }
        .title-way {
          padding-right: 15px;
        }
        .control {
          text-align: right;
        }
      }
    }
  }
}
</style>